package com.clstu.datasource;

import com.clstu.utils.Actor;
import com.clstu.utils.JDBCUtils;
import org.testng.annotations.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;

/***
 * 测试JdbcUtilsByDruid工具类的使用
 */
public class JdbcUtilsByDruidUse {
    @Test//测试工具类的使用
    public void method() throws SQLException {
        Connection connection = JdbcUtilsByDruid.getConnection();
        System.out.println(connection.getClass());//com.alibaba.druid.pool.DruidPooledConnection
        String sql="select * from actor order by id";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        while (resultSet.next()){//打印结果
            System.out.println(resultSet.getInt("id")+"\t"+resultSet.getString("sex")+
                    "\t"+resultSet.getString("name")+"\t"+resultSet.getDate("birthday"));
        }
        JdbcUtilsByDruid.close(resultSet,preparedStatement,connection);//因为运行类型的不一样,所以都是调用close()方法,执行的可能是不同的操作
    }


    @Test//演示用土方法完成对resultSet的封装------>Arraylist<actor>   Actor需要自己定义(根据表的属性创建)
    // (因为resultSet本身不好用,需要保持连接,得到获得属性的方法也不完美..)
    public void selectToArrayList() throws SQLException {
        Connection connection = JdbcUtilsByDruid.getConnection();
        System.out.println(connection.getClass());//com.alibaba.druid.pool.DruidPooledConnection
        String sql="select * from actor order by id";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        ResultSet resultSet = preparedStatement.executeQuery();
        ArrayList<Actor> actors = new ArrayList<>();
        while (resultSet.next()){//装入到集合种
            actors.add(new Actor(resultSet.getInt("id") , resultSet.getString("sex")
                    ,resultSet.getString("name"),resultSet.getDate("birthday")));
        }
        JdbcUtilsByDruid.close(resultSet,preparedStatement,connection);//在输出前就可以关闭连接了
        for (Actor actor : actors) {//遍历输出查询结果
            System.out.println(actor);
        }

    }

}
